package com.jhh.pay.center.actor;

import com.jhh.pay.center.model.PayChannel;
import com.jhh.pay.center.model.TradeState;
import com.jhh.pay.center.service.PayChannelService;
import com.jhh.pay.center.service.cloud.PayChannelTemplate;
import com.jhh.pay.center.service.cloud.message.BankInfo;
import com.jhh.pay.center.service.cloud.message.TradeResult;
import com.jhh.pay.center.service.cloud.message.TradePayBody;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.config.ConfigurableBeanFactory;
import org.springframework.context.annotation.Scope;
import org.springframework.stereotype.Service;

/**
 * @author tangxd
 * @Description: 打款交易ACTOR
 * @date 2017/12/11
 */
@Service("PayTradeActor")
@Scope(ConfigurableBeanFactory.SCOPE_PROTOTYPE)
@Slf4j
public class PayTradeActor extends TradeActor {

    @Autowired
    private PayChannelTemplate template;

    @Autowired
    private PayChannelService channelService;

    @Override
    public Receive createReceive() {
        return receiveBuilder()
                .match(TradeData.class, type -> {

                    PayChannel channel = channelService.get(type.getOrder().getChannelId());

                    TradePayBody tp = new TradePayBody();
                    tp.setSid(type.getOrder().getId());
                    tp.setOrderNo(type.getOrder().getOrderNo());
                    if (!setChannelCfg(tp, channel)) {
                        return;
                    }
                    BankInfo info = new BankInfo();
                    info.setBankCard(type.getOrder().getBankCard());
                    info.setBankMobile(type.getOrder().getBankMobile());
                    info.setBankNo(type.getOrder().getBankNo());
                    info.setPersonalName(type.getOrder().getPersonalName());
                    tp.setBankInfo(info);
                    tp.setMoney(type.getOrder().getMoney());
                    setMessageExtension(tp, channel, type.getOrder());

                    try {
                        TradeResult mr = template.pay(channel, tp);
                        sender().tell(mr, self());
                    } catch (Exception e) {
                        e.printStackTrace();
                        log.error(e.getMessage(), e);
                        sender().tell(TradeResult.create(TradeState.ERROR, "SYS:PCH:0003", e.getMessage()), self());
                    }
                })
                .build();
    }
}
